package com.itboye.mengwu.app.ui.aiwujia;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import test.FlowLayout;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DensityUtil;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.inageview.ImagePagerActivity;
import com.itboye.inageview.NoScrollGridAdapter;
import com.itboye.inageview.NoScrollGridView;
import com.itboye.inageview.RoundImageView;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.adapter.YuErJingCommentAdapter;
import com.itboye.mengwu.app.ui.aizhiwu.GeRenActivity;
import com.itboye.mengwu.data.model.BiaoQianModel;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply;
import com.itboye.mengwu.data.presenter.BiaoQianPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.luntan.comment.view.MyListView;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListViewFooter;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

/**
 * 
 * 
 * 2016.5.04
 * 
 */
public class ActivityToBiaoQian extends BaseActivity implements Observer,
		IXListViewListener {

	private XListView listview;
	View headermamafenxiang;
	TextView hot_talk;
	TieZiPresenter presenter;
	private String uid;
	private MyAdapter adapter;
	ArrayList<TieZiBaoHanReply.GetAList> aLists = new ArrayList<TieZiBaoHanReply.GetAList>();
	TextView biaoqian_show;
	TextView baby_years;
	TextView baby_sex;
	String biaoqian;
	private XListViewFooter mFooterView = null;

	BiaoQianPresenter biaoqianPresenter;
	ArrayList<BiaoQianModel> biaoqianlist = new ArrayList<BiaoQianModel>();
	FlowLayout flowLayout;
	FlowLayout flowLayout2;
	int pageNo = 1;
	LuntanTieZiBean model = new LuntanTieZiBean();
	TextView txt_title;
	ImageView back;
	String title;
	String biaoqianID;
	String type = "load";

	@Override
	public int initView() {

		return R.layout.activity_tobiaoqian;
	}

	@Override
	public void onMyCreate() {
		title = getIntent().getStringExtra("biaoqian");
		txt_title.setText(title);
		showProgressDialog("数据加载中，请稍后", true);
		presenter = new TieZiPresenter(this);
		biaoqianPresenter = new BiaoQianPresenter(this);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		biaoqianPresenter.QueryBiaoQian(uid, "2", "10");
		biaoqianID = getIntent().getStringExtra("biaoqianID");
		listview.removeFooterView(mFooterView);
		presenter.TieZiBiaoQian(uid, biaoqianID, "", pageNo + "");
		headermamafenxiang = LayoutInflater.from(this).inflate(
				R.layout.biaoqian_header, null);
		flowLayout = (FlowLayout) headermamafenxiang
				.findViewById(R.id.flowLayout);
		listview.addHeaderView(headermamafenxiang);

		adapter = new MyAdapter(this, ImgOnClickListener);
		listview.setAdapter(adapter);
		listview.setXListViewListener(this);
		listview.setPullLoadEnable(true);
		listview.setPullRefreshEnable(true);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 > 1) {
					Intent intent2 = new Intent(ActivityToBiaoQian.this,
							YuErJingMomDetailActivity.class);
					intent2.putExtra("tid", aLists.get(arg2 - 2).getTid());
					startActivity(intent2);
				}

			}
		});
	}

	OnClickListener ImgOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			String tid = (String) v.getTag(R.id.tag_first);
			String isFav = (String) v.getTag(R.id.tag_second);

			uid = SPUtils.get(ActivityToBiaoQian.this, null,
					SpPublicParams.UID, "") + "";

			if ("0".equals(isFav)) {
				showProgressDialog("请求提交中，请稍后", true);
				presenter.dianzan(uid, "1", tid);

			} else {
				ByAlert.alert("已经点过赞了");

			}
		}
	};

	@SuppressWarnings("deprecation")
	private void setbiaoqianname() {
		for (int i = 0; i < biaoqianlist.size(); i++) {
			View view = LayoutInflater.from(ActivityToBiaoQian.this).inflate(
					R.layout.textview, null);
			TextView textView = (TextView) view.findViewById(R.id.text);
			ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
			img_del.setVisibility(View.GONE);
			textView.setText(biaoqianlist.get(i).getName());
			textView.setTextColor(R.color.main_textcolor);
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.biaoqianshape));
			Log.d("hu", biaoqianlist.get(i).getName());
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			view.setTag(i);
			flowLayout.addView(view, lP);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ActivityToBiaoQian.this,
							ActivityToBiaoQian.class);
					intent.putExtra("biaoqian",
							biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
									.getName());
					intent.putExtra("biaoqianID",
							biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
									.getId());
					overridePendingTransition(0, 0);
					startActivity(intent);
					finish();
				}
			});
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == BiaoQianPresenter.queryBiaoQIan_success) {
				biaoqianlist
						.addAll((ArrayList<BiaoQianModel>) entity.getData());
				setbiaoqianname();
			}

			if (entity.getEventType() == TieZiPresenter.GetTieZiBaioQianSuccess) {
				if (type == "load") {

				} else {
					aLists.clear();
				}
				aLists.addAll(((TieZiBaoHanReply) entity.getData()).getList());
				adapter.notifyDataSetChanged();
				stopLoad();
				try {
					closeProgressDialog();
				} catch (Exception e) {

				}
			} else if (entity.getEventType() == TieZiPresenter.GetTieZiBaioQianFail) {
				ByAlert.alert("没有数据");
				listview.setPullLoadEnable(false);
				adapter.notifyDataSetChanged();
				stopLoad();
			}
			if (entity.getEventType() == TieZiPresenter.DianzanSuccess) {
				ByAlert.alert(entity.getData() + "");
				presenter.getInfo(model);
			} else if (entity.getEventType() == TieZiPresenter.DianzanyeFail) {
				ByAlert.alert(entity.getData() + "");
			}
		} else {
			ByAlert.alert("没数据啦");
			listview.setPullLoadEnable(false);
			stopLoad();
		}

	}

	class MyAdapter extends BaseAdapter {
		String isFav = "0";

		OnClickListener imgOnClickListener;
		Context context;

		public MyAdapter(Context context, OnClickListener imgOnClickListener) {
			this.context = context;
			this.imgOnClickListener = imgOnClickListener;
		}

		@Override
		public int getCount() {
			return aLists == null ? 0 : aLists.size();
		}

		@Override
		public Object getItem(int position) {
			return aLists == null ? 0 : aLists.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings({ "unused", "deprecation" })
		@SuppressLint("SimpleDateFormat")
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (holder == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.yuer_list_item, null);
				holder.content_flowlayout = (FlowLayout) convertView
						.findViewById(R.id.content_flowlayout);
				holder.tv = (TextView) convertView.findViewById(R.id.tv);
				holder.question_show = (TextView) convertView
						.findViewById(R.id.question_show);
				holder.author_headewrshow = (ImageView) convertView
						.findViewById(R.id.author_headewrshow);
				holder.baby_sex = (TextView) convertView
						.findViewById(R.id.baby_sex);
				holder.baby_years = (TextView) convertView
						.findViewById(R.id.baby_years);
				holder.pinglunderen = (LinearLayout) convertView
						.findViewById(R.id.pinglunderen);
				holder.biaoqian_lin = (RelativeLayout) convertView
						.findViewById(R.id.biaoqian_lin);
				holder.pinglunrenshu = (TextView) convertView
						.findViewById(R.id.pinglunrenshu);
				holder.pinglun = (MyListView) convertView
						.findViewById(R.id.pinglun);
				holder.author_headewrshow = (ImageView) convertView
						.findViewById(R.id.author_headewrshow);
				holder.collection_num = (TextView) convertView
						.findViewById(R.id.collection_num);
				holder.delete = (ImageView) convertView
						.findViewById(R.id.delete);
				holder.gridview = (NoScrollGridView) convertView
						.findViewById(R.id.gridview);
				// holder.img_1 = (ImageView)
				// convertView.findViewById(R.id.img_1);
				// holder.img_2 = (ImageView)
				// convertView.findViewById(R.id.img_2);
				// holder.img_3 = (ImageView)
				// convertView.findViewById(R.id.img_3);
				holder.author_name = (TextView) convertView
						.findViewById(R.id.author_name);
				holder.imgCollectionNum = (ImageView) convertView
						.findViewById(R.id.imgCollectionNum);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.delete.setVisibility(View.GONE);
			if (aLists.get(position).getMessage() != null) {
				holder.question_show.setText("\t"
						+ aLists.get(position).getMessage());
			}

			if ("1".equals(aLists.get(position).getIsLike())) {
				holder.imgCollectionNum.setSelected(true);

			} else if ("0".equals(aLists.get(position).getIsLike())) {
				holder.imgCollectionNum.setSelected(false);
			}
			if (aLists.get(position).getTag_info() != null
					&& aLists.get(position).getTag_info().size() != 0) {

				for (int i = 0; i < aLists.get(position).getTag_info().size(); i++) {
					View view = LayoutInflater.from(ActivityToBiaoQian.this)
							.inflate(R.layout.textview, null);
					TextView textView = (TextView) view.findViewById(R.id.text);
					textView.setTextColor(getResources().getColor(
							R.color.main_color));
					ImageView img_del = (ImageView) view
							.findViewById(R.id.img_del);
					img_del.setVisibility(View.GONE);
					textView.setBackgroundColor(getResources().getColor(
							R.color.white));
					TextView tx[] = new TextView[aLists.get(position)
							.getTag_info().size()];
					textView.setText("#"
							+ aLists.get(position).getTag_info().get(i)
									.getName() + "#");
					android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
							android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
							android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
					int right = DensityUtil.dip2px(1);
					lP.setMargins(0, 0, 0, 0);
					view.setTag(i);
					holder.content_flowlayout.addView(view, lP);
					view.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(ActivityToBiaoQian.this,
									ActivityToBiaoQian.class);
							intent.putExtra(
									"biaoqian",
									aLists.get(position)
											.getTag_info()
											.get(Integer.parseInt(v.getTag()
													+ "")).getName());

							intent.putExtra(
									"biaoqianID",
									aLists.get(position)
											.getTag_info()
											.get(Integer.parseInt(v.getTag()
													+ "")).getId());
							overridePendingTransition(0, 0);
							startActivity(intent);
							finish();
						}
					});
				}
			} else {
				holder.biaoqian_lin.setVisibility(View.GONE);
			}

			holder.author_name.setText(aLists.get(position).getauthor());

			if (aLists.get(position).getBabyDefault() != null) {
				if ("0".equals(aLists.get(position).getBabyDefault().getSex())) {
					holder.baby_sex.setText("女宝");
				} else if ("1".equals(aLists.get(position).getBabyDefault()
						.getSex())) {
					holder.baby_sex.setText("男宝");

				} else {
					holder.baby_sex.setText("孕育中");
				}

				SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy年MM月dd日");
				Calendar calendar = Calendar.getInstance();
				int yearNow = calendar.get(Calendar.YEAR);
				int monthNow = calendar.get(Calendar.MONTH);
				int dayNow = calendar.get(Calendar.DAY_OF_MONTH);
				Log.d("hu-----", yearNow + "monthNow-----" + "-------dayBirth"
						+ monthNow + "n" + dayNow);
				Calendar calendar2 = Calendar.getInstance();
				if (aLists.get(position).getBabyDefault().getBirthday() != null) {
					long timews = Long.valueOf(aLists.get(position)
							.getBabyDefault().getBirthday());
					Date date = new Date(timews * 1000L);
					calendar2.setTime(date);
					int yearBirth = calendar2.get(Calendar.YEAR);
					int monthBirth = calendar2.get(Calendar.MONTH);
					int dayBirth = calendar2.get(Calendar.DAY_OF_MONTH);
					Log.d("hu-----2", yearBirth + "monthBirth-----"
							+ "-------dayBirth" + monthBirth + "n" + dayBirth);
					int age = yearNow - yearBirth;
					int month = monthNow - monthBirth;
					int day = dayNow - dayBirth;
					if (day < 0) {
						month -= 1;
						calendar2.add(Calendar.MONTH, -1);// 得到上一个月，用来得到上个月的天数。
						day = day
								+ calendar2
										.getActualMaximum(Calendar.DAY_OF_MONTH);
					}
					if (month < 0) {
						month = (month + 12) % 12;
						age--;
					}
					int days = day + 1;
					int months = month + 1;
					if (age == 0) {
						if (month == 0) {
							holder.baby_years.setText(days + "天");
						} else {
							holder.baby_years
									.setText(months + "月" + days + "天");
						}
					} else {
						if (month == 0) {
							holder.baby_years.setText(age + "岁" + days + "天");
						} else {
							holder.baby_years.setText(age + "岁" + months + "月"
									+ days + "天");
						}
					}

				} else {
					holder.baby_sex.setVisibility(View.GONE);
					holder.baby_years.setVisibility(View.GONE);
				}
			} else {
				holder.baby_sex.setVisibility(View.GONE);
				holder.baby_years.setVisibility(View.GONE);
				holder.author_name.setGravity(Gravity.CENTER_VERTICAL);
			}
			if (aLists.get(position).getImg() != null) {
				final ArrayList<String> arrayImage = aLists.get(position)
						.getImg();
				// if (arrayImage == null || arrayImage.size() == 0) { //
				// 没有图片资源就隐藏GridView
				// viewHolder.gridview.setVisibility(View.GONE);
				// } else {
				holder.gridview.setAdapter(new NoScrollGridAdapter(context,
						arrayImage));
				// }
				// 使用ImageLoader加载网络图片
				// XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
				// + aLists.get(position).getHead(), holder.iv_avatar);
				// 点击回帖九宫格，查看大图
				holder.gridview
						.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								// TODO Auto-generated method stub
								imageBrower(position, arrayImage);
							}
						});

			}
			holder.pinglunderen.removeAllViews();
			if (aLists.get(position).getReplyInfo() != null) {
				for (int i = 0; i < aLists.get(position).getReplyInfo()
						.getList().size(); i++) {
					RoundImageView imageView = new RoundImageView(
							ActivityToBiaoQian.this);
					LayoutParams layoutParams = new LayoutParams(50,
							LayoutParams.MATCH_PARENT);
					layoutParams.setMargins(5, 5, 5, 5);
					imageView.setTag(R.id.pinglunderen, aLists.get(position)
							.getLikeInfo().get(i).getUid());

					if (aLists.get(position).getLikeInfo().get(i).getHead() == null
							|| "".equals(aLists.get(position).getLikeInfo()
									.get(i).getHead())) {
						if ("1".equals(aLists.get(position).getLikeInfo()
								.get(i).getSex())) {
							// imageView.setImageResource(R.drawable.male);
							imageView.setBackgroundResource(R.drawable.male);
						} else {
							imageView.setImageResource(R.drawable.female);
						}
					} else {
						if (!aLists.get(position).getLikeInfo().get(i)
								.getHead().startsWith("http")) {
							XImageLoader.load(
									GlobalConfig.API_URL
											+ "/picture/index?id="
											+ aLists.get(position)
													.getLikeInfo().get(i)
													.getHead(), imageView);
						} else {
							XImageLoader.load(aLists.get(position)
									.getLikeInfo().get(i).getHead(), imageView);
						}

					}
					holder.pinglunderen.addView(imageView, layoutParams);
					imageView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(context,
									GeRenActivity.class);
							intent.putExtra(
									"uid",
									SPUtils.get(context, null,
											SpPublicParams.UID, "") + "");
							intent.putExtra("fromUid",
									v.getTag(R.id.pinglunderen) + "");
							context.startActivity(intent);
						}
					});
				}

				holder.pinglunrenshu.setText(aLists.get(position)
						.getReplyInfo().getCount());// 评论人数
			}
			holder.collection_num.setText(aLists.get(position).getLikes());// 收藏人数

			if (aLists.get(position).getHead() == null
					|| "".equals(aLists.get(position).getHead())) {
				if ("1".equals(aLists.get(position).getSex())) {
					// imageView.setImageResource(R.drawable.male);
					holder.author_headewrshow
							.setBackgroundResource(R.drawable.male);
				} else {
					holder.author_headewrshow
							.setImageResource(R.drawable.female);
				}
			} else {
				if (!aLists.get(position).getHead().startsWith("http")) {
					XImageLoader.load(GlobalConfig.API_URL
							+ "/picture/index?id="
							+ aLists.get(position).getHead(),
							holder.author_headewrshow);
				} else {
					XImageLoader.load(aLists.get(position).getHead(),
							holder.author_headewrshow);
				}

			}
			holder.author_headewrshow.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					Intent intent = new Intent(context, GeRenActivity.class);
					intent.putExtra("uid",
							SPUtils.get(context, null, SpPublicParams.UID, "")
									+ "");
					intent.putExtra("fromUid", aLists.get(position)
							.getAuthorId() + "");
					startActivity(intent);
				}
			});
			// if (aLists.get(position).getHead() != null) {
			// if (!aLists.get(position).getHead().startsWith("http:")) {
			// XImageLoader.load(GlobalConfig.API_URL
			// + "/picture/index?id="
			// + aLists.get(position).getHead(),
			// holder.author_headewrshow);
			// } else {
			// XImageLoader.load(aLists.get(position).getHead(),
			// holder.author_headewrshow);
			// }
			// }
			if (aLists.get(position).getReplyInfo() != null) {
				if (aLists.get(position).getReplyInfo().getCount() != "0") {//
					// 判断是否有回复
					holder.pinglun.setAdapter(new YuErJingCommentAdapter(
							context, aLists.get(position).getReplyInfo()
									.getList(), position));
					if (aLists.get(position).getReplyInfo().getList().size() > 0)
						System.out.println("评论的条数"
								+ aLists.get(position).getReplyInfo().getList()
										.size());
				}
			}
			holder.imgCollectionNum.setTag(R.id.tag_first, aLists.get(position)
					.getTid());
			holder.imgCollectionNum.setTag(R.id.tag_second, aLists
					.get(position).getIsLike());
			holder.imgCollectionNum.setOnClickListener(imgOnClickListener);
			return convertView;
		}

		class ViewHolder {
			MyListView pinglun;
			TextView author_name, pinglunrenshu, baby_years, baby_sex,
					collection_num;
			TextView question_show, hot_talk, tv;
			LinearLayout pinglunderen;
			ImageView author_headewrshow, imgCollectionNum, delete;
			FlowLayout content_flowlayout;
			RelativeLayout biaoqian_lin;
			NoScrollGridView gridview;
		}
	}

	@Override
	public void onRefresh() {
		showProgressDialog("正在刷新哦,请稍后", true);
		pageNo = 1;
		type = "type";
		// model.setUid(uid);
		// model.setFid(6 + "");
		// model.setPage_no(pageNo + "");
		// presenter.getInfo(model);
		presenter.TieZiBiaoQian(uid, biaoqianID, "", pageNo + "");
	}

	protected void imageBrower(int position, ArrayList<String> urls2) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		this.startActivity(intent);
	}

	@Override
	public void onLoadMore() {
		showProgressDialog("正在加载更多哦,请稍后", true);

		pageNo++;
		type = "load";
		// model.setUid(uid);
		// model.setFid(6 + "");
		// model.setPage_no(pageNo + "");
		// presenter.getInfo(model);
		presenter.TieZiBiaoQian(uid, biaoqianID, "", pageNo + "");
	}

	public void stopLoad() {
		listview.stopLoadMore();
		listview.stopRefresh();
	}

}
